import { defineStore } from 'pinia'
import getLogin from '@/api/login'

export const useLoginStore = defineStore('login', {
  state: () => ({
    Authorization: '',
    avatar: '',
    nickName: ''
  }),
  actions: {
    // 修改login方法，确保登录失败时抛出错误
    async login(username, password) {
      try {
        let res = await getLogin(username, password)
        console.log(res)

        // 增加接口返回状态判断（根据实际接口规范调整）
        if (!res || !res.data || !res.data.token) {
          throw new Error('登录失败，未获取到token')
        }

        let { userInfo, token } = res.data
        localStorage.setItem('Authorization', token)
        localStorage.setItem('avatar', userInfo.avatarUrl || '')
        localStorage.setItem('nickName', userInfo.nickName || '')

        this.Authorization = token
        this.avatar = userInfo.avatarUrl
        this.nickName = userInfo.nickName

        return true // 登录成功返回true
      } catch (error) {
        console.log(error)
        throw error // 抛出错误让组件捕获
      }
    }
  },
  persist: false
})
